package com.campus.food.controller;

import com.campus.food.model.dto.LoginDTO;
import com.campus.food.model.dto.RegisterDTO;
import com.campus.food.model.dto.PasswordDTO;
import com.campus.food.model.entity.Merchant;
import com.campus.food.model.entity.User;
import com.campus.food.model.vo.Result;
import com.campus.food.service.MerchantService;
import com.campus.food.service.UserService;
import com.campus.food.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

/**
 * 用户控制器
 * 处理用户相关的HTTP请求
 * 
 * @author Claude3.7 Sonnet
 * @since 2025-05-29
 */
@RestController
@RequestMapping("/api/users")
@Validated
public class UserController {
    
    @Autowired
    private UserService userService;

    @Autowired
    private MerchantService merchantService;
    
    /**
     * 用户注册
     * POST /api/users/register
     */
    @PostMapping("/register")
    public Result<User> register(@Valid @RequestBody RegisterDTO registerDTO, HttpServletRequest request) {
        // 验证两次密码是否一致
        if (!registerDTO.getPassword().equals(registerDTO.getConfirmPassword())) {
            return Result.failure(400, "两次输入的密码不一致", request.getRequestURI());
        }
        
        User user = userService.register(registerDTO);
        // 清除密码字段后返回
        user.setPassword(null);
        return Result.success("注册成功", user);
    }
    
    /**
     * 用户登录
     * POST /api/users/login
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@Valid @RequestBody LoginDTO loginDTO) {
        String token = userService.login(loginDTO);
        User user = userService.getUserByUsername(loginDTO.getUsername());
        Merchant merchant = merchantService.getMerchantByUserId(user.getId());
        user.setMerchantId(merchant == null ? null : merchant.getId());

        Map<String, Object> data = new HashMap<>();
        data.put("token", token);
        user.setPassword("");
        data.put("user", user);
//        data.put("merchant", merchant);
        
        return Result.success("登录成功", data);
    }
    
    /**
     * 获取用户信息
     * GET /api/users/{id}
     */
    @GetMapping("/{id}")
    public Result<User> getUserById(@PathVariable @NotNull Long id, HttpServletRequest request) {
        User user = userService.getUserById(id);
        // 清除密码字段
        user.setPassword(null);
        return Result.success(user);
    }
    
    /**
     * 根据用户名获取用户信息
     * GET /api/users/username/{username}
     */
    @GetMapping("/username/{username}")
    public Result<User> getUserByUsername(@PathVariable String username, HttpServletRequest request) {
        User user = userService.getUserByUsername(username);
        if (user == null) {
            return Result.failure(404, "用户不存在", request.getRequestURI());
        }
        // 清除密码字段
        user.setPassword(null);
        return Result.success(user);
    }
    
    /**
     * 更新用户信息
     * PUT /api/users/{id}
     */
    @PutMapping("/{id}")
    public Result<Void> updateUser(@PathVariable @NotNull Long id, 
                                  @RequestBody User user) {
        user.setId(id);
        boolean success = userService.updateUser(user);
        if (success) {
            return Result.success("更新成功", null);
        } else {
            return Result.failure(500, "更新失败", null);
        }
    }
    
    /**
     * 更新用户状态
     * PUT /api/users/{id}/status
     */
    @PutMapping("/{id}/status")
    public Result<Void> updateUserStatus(@PathVariable @NotNull Long id,
                                        @RequestParam @NotNull Integer status) {
        boolean success = userService.updateUserStatus(id, status);
        if (success) {
            String message = status == 1 ? "启用成功" : "禁用成功";
            return Result.success(message, null);
        } else {
            return Result.failure(500, "状态更新失败", null);
        }
    }
    
    /**
     * 获取用户列表（分页，管理员专用）
     * GET /api/users
     */
    @GetMapping
    public Result<List<User>> getUserList(@RequestParam(defaultValue = "1") int page,
                                        @RequestParam(defaultValue = "10") int size,
                                        @RequestParam(required = false) String username,
                                        @RequestParam(required = false) String realName,
                                        @RequestParam(required = false) Integer role,
                                        @RequestParam(required = false) Integer status) {
        List<User> users = userService.getUserList(page, size, username, realName, role, status);
        long total = userService.getUserCount(username, realName, role, status);
        
        // 清除所有用户的密码字段
        users.forEach(user -> user.setPassword(null));
        
        return Result.success(users);
    }
    
    /**
     * 根据角色获取用户列表
     * GET /api/users/role/{role}
     */
    @GetMapping("/role/{role}")
    public Result<List<User>> getUsersByRole(@PathVariable @NotNull Integer role) {
        List<User> users = userService.getUsersByRole(role);
        // 清除所有用户的密码字段
        users.forEach(user -> user.setPassword(null));
        return Result.success(users);
    }
    
    /**
     * 检查用户名是否存在
     * GET /api/users/check/username/{username}
     */
    @GetMapping("/check/username/{username}")
    public Result<Boolean> checkUsername(@PathVariable String username) {
        boolean exists = userService.existsByUsername(username);
        return Result.success(exists);
    }
    
    /**
     * 检查手机号是否存在
     * GET /api/users/check/phone/{phone}
     */
    @GetMapping("/check/phone/{phone}")
    public Result<Boolean> checkPhone(@PathVariable String phone) {
        boolean exists = userService.existsByPhone(phone);
        return Result.success(exists);
    }
    
    /**
     * 检查邮箱是否存在
     * GET /api/users/check/email/{email}")
     */
    @GetMapping("/check/email/{email}")
    public Result<Boolean> checkEmail(@PathVariable String email) {
        boolean exists = userService.existsByEmail(email);
        return Result.success(exists);
    }
    
    /**
     * 删除用户（管理员专用）
     * DELETE /api/users/{id}
     */
    @DeleteMapping("/{id}")
    public Result<Void> deleteUser(@PathVariable @NotNull Long id, HttpServletRequest request) {
        boolean success = userService.deleteUser(id);
        if (success) {
            return Result.success("删除成功", null);
        } else {
            return Result.failure(500, "删除失败", request.getRequestURI());
        }
    }
    
    /**
     * 更新最后登录时间
     * PUT /api/users/{id}/last-login
     */
    @PutMapping("/{id}/last-login")
    public Result<Void> updateLastLoginTime(@PathVariable @NotNull Long id, HttpServletRequest request) {
        boolean success = userService.updateLastLoginTime(id);
        if (success) {
            return Result.success("更新成功", null);
        } else {
            return Result.failure(500, "更新失败", request.getRequestURI());
        }
    }
    
    /**
     * 修改密码
     * PUT /api/users/password
     */
    @PutMapping("/password")
    public Result<Void> changePassword(@Valid @RequestBody PasswordDTO passwordDTO) {
        boolean success = userService.changePassword(
            passwordDTO.getUserId(),
            passwordDTO.getOldPassword(),
            passwordDTO.getNewPassword()
        );
        
        if (success) {
            return Result.success("密码修改成功", null);
        } else {
            return Result.failure(400, "密码修改失败，请检查原密码是否正确", null);
        }
    }
    
    /**
     * 上传用户头像
     * POST /api/users/avatar
     */
    @PostMapping("/avatar")
    public Result<Map<String, String>> uploadAvatar(
            @RequestParam("file") MultipartFile file,
            @RequestParam("userId") Long userId) {
        
        if (file.isEmpty()) {
            return Result.failure(400, "请选择要上传的文件", null);
        }
        
        try {
            // 生成文件名
            String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
            // 文件存储路径
            String filePath = "uploads/avatars/" + fileName;
            
            // 确保目录存在
            File destDir = new File("uploads/avatars");
            if (!destDir.exists()) {
                destDir.mkdirs();
            }
            
            // 保存文件
            File destFile = new File(filePath);
            file.transferTo(destFile);
            
            // 更新用户头像URL
            User user = new User();
            user.setId(userId);
            user.setAvatar("/api/uploads/avatars/" + fileName);
            userService.updateUser(user);
            
            Map<String, String> response = new HashMap<>();
            response.put("url", "/api/uploads/avatars/" + fileName);
            
            return Result.success("头像上传成功", response);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.failure(500, "头像上传失败", null);
        }
    }
} 